package my.edu.handler;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import my.edu.security.userEntity.UserDetail;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Configuration
public class MyMateObjectHandler implements MetaObjectHandler {

    /**
     * 添加时  自动填充
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("mybatisplus公共字段填充[insert]...");
        //获取实体类中所有的属性名
        String[] getterNames = metaObject.getObjectWrapper().getGetterNames();
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        Long userid;
        if (user != null) {
            userid = user.getId();
            String username = user.getName();
            if (ArrayUtil.contains(getterNames, "createdBy"))   metaObject.setValue("createdBy", userid);//新增人ID
            if (ArrayUtil.contains(getterNames, "createdName"))  metaObject.setValue("createdName", username);//创建人名称
        }
        if (ArrayUtil.contains(getterNames, "createTime"))  metaObject.setValue("createTime", LocalDateTime.now());//创建时间
        if (ArrayUtil.contains(getterNames, "createdTime"))  metaObject.setValue("createdTime", LocalDateTime.now());//创建时间
    }

    /**
     * 更新时 自动填充
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("mybatisplus公共字段填充[update]...");
        String[] getterNames = metaObject.getObjectWrapper().getGetterNames();
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        Long userid;
        if (user != null) {
            userid = user.getId();
            metaObject.setValue("updatedBy", userid);//修改人ID
            if (ArrayUtil.contains(getterNames, "updateName"))  metaObject.setValue("updateName", user.getName());//创建人名称

        }
         metaObject.setValue("updateTime", LocalDateTime.now());//修改时间
    }
}